<template>
<el-dialog :title="title" @close="closeFn" :visible="addAreaDialog" width="630px">
  <el-form ref="form" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="区域名称:" prop="regionName">
      <el-input v-model="form.regionName" autocomplete="off"
      style="width:360px"
      placeholder="请输入"></el-input>
    </el-form-item>
    <el-form-item label="备注说明:" prop="remark">
      <el-input type="textarea" :rows="3"
      style="width:360px"
      v-model="form.remark"
      placeholder="请输入备注(不超过40字)"></el-input>
    </el-form-item>
  </el-form>
  <el-row type="flex" justify="center">
          <el-button class="left" size="middle" @click="closeFn">取 消</el-button>
          <el-button class="right" size="middle" type="primary" @click="submit">确 定</el-button>
        </el-row>
</el-dialog>
</template>

<script>
import { addArea, editArea } from '@/api/place'
export default {
  props: {
    addAreaDialog: Boolean,
    tableData: Array,
    editRow: Object
  },
  data () {
    return {
      form: {
        regionName: '', // 区域名称
        remark: '' // 备注说明
      },
      rules: {
        regionName: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (this.editRow) callback()
              const res = this.tableData.some(item => {
                return item.name === value
              })
              res ? callback(new Error('已存在此区域地址')) : callback()
            }
          }
        ],
        remark: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title () {
      return this.editRow ? '修改区域' : '新增区域'
    }
  },
  methods: {
    edit () {
      this.$nextTick(() => {
        this.form.regionName = this.editRow.name
        this.form.remark = this.editRow.remark
      })
    },
    submit () {
      this.$refs.form.validate(async pass => {
        if (pass) {
          this.editRow
            ? await editArea({
              regionName: this.form.regionName,
              remark: this.form.remark,
              id: this.editRow.id
            })
            : await addArea(this.form)
          this.$message.success(`${this.editRow ? '修改' : '新增'}` + '成功')
          this.$parent.getAreaList()
          this.closeFn()
        }
      })
    },
    closeFn () {
      this.$emit('update:addAreaDialog', false)
      this.$refs.form.resetFields()
    }

  }
}
</script>

<style lang="less" scoped>
.left {
  transform: translateX(-15px);
}
.right{
  transform: translateX(15px);
  background-color: #ff8337;
}
</style>
